package com.lottery.service.qiuqiu.accoutService;

import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.qiuqiu.accoutDao.LoaclauthDao;
import com.lottery.dao.qiuqiu.accoutDao.LoginInfoDao;
import com.lottery.dao.qiuqiu.accoutDao.UserDao;
import com.lottery.dao.qiuqiu.lobbyDao.BettinginfoDao;
import com.lottery.dao.qiuqiu.statisticsDao.AgencyDao;
import com.lottery.dao.qiuqiu.wealthDao.AccountDao;
import com.lottery.dao.qiuqiu.wealthDao.AccountTransactionDao;
import com.lottery.dto.*;
import com.lottery.entity.*;
import com.lottery.initData.InitData;
import com.lottery.service.qiuqiu.JedisClient;
import com.lottery.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

@Service
public class LocalauthService {
    @Autowired
    private LoaclauthDao loaclauthdao;

    @Autowired
    private UserDao userdao;

    @Autowired
    private JedisClient jedisClient;

    @Autowired
    private LoginInfoDao logindao;

    @Autowired
    private AccountDao accountDao;

    @Resource
    private BettinginfoDao bettinginfoDao;

    @Resource
    private AccountTransactionDao accountTransactionDao;

    @Resource
    private AgencyDao agencyDao;

    // 用户token的key
    @Value("${TOKEN}")
    private String TOKEN;

    @Value("${SPREADCODE}")
    private String SPREADCODE;

    // #用户微信登录token的key
    @Value("${TOKEN1}")
    private String TOKEN1;

    // #生成的验证码以key存储进 jedis
    @Value("${LOGINSYSTEM}")
    private String LOGINSYSTEM;

    // #生成的手机短信验证码以 key的 形式存储
    @Value("${LOGINSYSTEM1}")
    private String LOGINSYSTEM1;

    @Value("${SMSKEY}")
    private String SMSKEY;

    @Value("${SMSSMARK}")
    private String SMSSMARK;


    // 日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 登录

    public String login(String phoneNum, String password, String deviceId, String hostAddr, int loginType) {
        JSONObject jObject = new JSONObject();
        User user = new User();
        logger.info("password*******************:{}", password);
        String pwd = UtilsDto.crypt(password);
        logger.info("pwd*******************:{}", pwd);
        // 登录时进行比对
        try {
            if (loginType == 1) {
                String tmpStr = phoneNum + "," + System.currentTimeMillis();
                String token = UtilsDto.crypt(tmpStr);
                jObject.put("token", token);
                String touristName = RandCodeUtil.randCode(5);
                jObject.put("nickName", touristName);

                Long index = jedisClient.incr("touristindex");
                int touristId = (int) (index + 1100000000);

                jedisClient.hset(touristId + "", "amount", 1000 + "");
                jObject.put("userId", touristId);
                jObject.put("loginType", loginType);
                jObject.put("deviceId", deviceId);

                Tourist tourist = new Tourist();
                tourist.setTouristId(touristId);
                tourist.setTouristName(touristName);
                tourist.setDeviceId(deviceId);
                TouristData.touristInfo.put(touristId, tourist);
                jedisClient.set(String.valueOf(TOKEN + touristId), token);
                jedisClient.expire(TOKEN + touristId, 60 * 60);
                jedisClient.expire(touristId + "", 60 * 60);

                //后续还得修改
//                ArrayList<Bettinginfo> sscBetList = new ArrayList<Bettinginfo>();
//                TouristData.touristBetting.put(touristId, sscBetList);
//                ArrayList<Bettinginfo> pc28BetList = new ArrayList<Bettinginfo>();
//                TouristData.touristPc28Betting.put(touristId, pc28BetList);
                jObject.put("result", "0");
            } else {
                if (phoneNum == null || phoneNum.trim().isEmpty()) {
                    jObject.put("result", "8");
                    jObject.put("msg", "用户名为空");
                    return jObject.toJSONString();
                }
                if (pwd == null || pwd.trim().isEmpty()) {
                    jObject.put("result", "1");
                    jObject.put("msg", "密码不能空");
                    return jObject.toJSONString();

                }
                logger.info(" username:{}", phoneNum);
                // 查询登录表信息
                Loaclauth loaclauth = loaclauthdao.selectphone(phoneNum);
                logger.info(" loaclauth:{}", loaclauth);
                // 获取登录表中的信息
                if (loaclauth == null) {
                    jObject.put("result", "3");
                    jObject.put("msg", "用户不存在 ");
                    return jObject.toJSONString();
                }
                // 获取数据库中的密码
                // 密码 进行 对比!jse.equals(smscode)
                logger.info("password:{}--{}", pwd, loaclauth.getPassword());
                if (pwd.equals(loaclauth.getPassword())) {
                    user = userdao.selectId(loaclauth.getuserId());
                    String agencyId = user.getAgencyId();

                    if (agencyId.length() != 5) {
                        Agency agency = agencyDao.selectAgency(agencyId);
                        agencyId = agency.getProxyRefAgency() + "";
                    }
                    Date date = new Date();
                    if (!"88888".equals(agencyId)) {
                        Timestamp time = InitData.effctiveTimes.get(agencyId);
                        if (date.getTime() > time.getTime()) {
                            jObject.put("result", 99);
                            jObject.put("msg", "平台使用期限已到期");
                            return jObject.toJSONString();
                        }
                    }
                    Agency ag = agencyDao.selectAgency(agencyId);
                    if(null == ag){
                        jObject.put("result",98);
                        jObject.put("msg", "您在的平台不存在,请联系客服");
                        return jObject.toJSONString();
                    }


                    // 登录成功
                    // 返回用户 信息
                    LoginInfo login = new LoginInfo();
                    // 生成一个token
                    String tmpStr = phoneNum + "," + System.currentTimeMillis();
                    String token = UtilsDto.crypt(tmpStr);
                    // 把token存入login_info
                    login.setToken(token);
                    login.setUserId(loaclauth.getuserId());
                    login.setUserMark(phoneNum);
                    login.setLoginTime(System.currentTimeMillis() / 1000);
                    login.setHostAddr(hostAddr);
                    login.setOnlineNum(InitData.ONLINE_MAP.get(agencyId).size());
                    login.setExpire(0);
                    login.setAgencyMark(agencyId);
                    login.setStrtime(DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss"));

                    logindao.insertloginfo(login);
                    // 把token存入jedisClient
                    jedisClient.set(String.valueOf(TOKEN + loaclauth.getuserId()), token);

                    if (user.getState().equals("0")) {
                        jObject.put("result", "4");
                        jObject.put("msg", "用户被冻结 ");
                        return jObject.toJSONString();
                    }
                    //onlineMap.put(loaclauth.getuserId(), (int) (System.currentTimeMillis() / 1000));
                    InitData.ONLINE_MAP.get(agencyId).put(user.getUserId(), (System.currentTimeMillis() / 1000));
                    logger.debug("online number:{}", InitData.ONLINE_MAP.size());
                    InitData.SSO_MAP.put(loaclauth.getuserId(), deviceId);


                    //计算昨日的收益
                    Integer userId = loaclauth.getuserId();
                    Calendar now = Calendar.getInstance();
                    now.setTime(date);
                    now.add(Calendar.DAY_OF_MONTH, -1);
                    String date2 = DateUtil.getFormatDate(now.getTime(), "yyyy-MM-dd");


                    //用户是否是代理商的判断
                    Agency agency = agencyDao.searchAgencyByUserId(loaclauth.getuserId());
                    if(agency != null){
                        jObject.put("agencyProxy",0);
                    }else{
                        jObject.put("agencyProxy",1);
                    }

                    double bet = bettinginfoDao.searchYesterdayBet(userId, date2);
                    double win = bettinginfoDao.searchYesterdayWin(userId, date2);
                    double yesterday = DealWithDouble.sub(win, bet, 2, 4);


                    logger.info("user:{}, phone_num:{}, pwd:{}", user, phoneNum, pwd);
                    jObject.put("yesterday", yesterday);
                    jObject.put("agencyMark", agencyId);
                    jObject.put("result", "0");
                    jObject.put("userId", loaclauth.getuserId());
                    jObject.put("headPic", user.getHeadPic());
                    String namestr = user.getUserName();
                    jObject.put("nickName", namestr);
                    jObject.put("phoneNum", phoneNum);
                    jObject.put("city", user.getCity());
                    jObject.put("myRecommendCode", user.getMyRecommendCode());
                    jObject.put("recommendCode", user.getRecommendCode());
                    jObject.put("realName", user.getRealName());
                    jObject.put("identityCard", user.getIdentityCard());
                    jObject.put("token", token);
                } else {
                    jObject.put("result", "4");
                    jObject.put("msg", "账户或密码输入错误");
                }
            }
        } catch (Exception e) {
            logger.error("login error,{}", e);
            jObject.put("result", "6");
            jObject.put("msg", "登陆失败");
        }
        return jObject.toJSONString();
    }

    /**
     * 校验注册
     * 1 user信息
     * 2 登入信息
     * 3 账户金额
     * 一项失败所有回滚
     *
     * @param password
     */

    @Transactional(rollbackFor = Exception.class)
    public void regist(String username, String password, String agencyId) throws Exception {
        //还可以加入相关判断,并针对性处理
        User user = new User();
        String nikename = RandCodeUtil.randCode(5);
        user.setUserName(nikename);
        user.setUserType(1);
        String createTime = DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss");
        user.setCreateTime(createTime);
        //判断用户是否有渠道商推荐码,没有则为平台默认用户
        if (agencyId.trim().isEmpty()) {
            user.setAgencyId("88888");
        } else {
            user.setAgencyId(agencyId);
        }
        userdao.insertUser(user);
        //获取自增生成的ID,并将用户名和密码存入loaclauth表
        int userId = user.getUserId();
        Loaclauth loaclauth = new Loaclauth();
        loaclauth.setuserId(userId);
        loaclauth.setPhoneNum(username);
        loaclauth.setPassword(password);
        loaclauthdao.insertloaclauth(loaclauth);
        // 注册成功后，向账户表插入一条数据（user_id）
        Account account = new Account();
        account.setUserId(userId);
        accountDao.insertAccount(account);
    }

    // 生成 一个不重复的deviceId
    public String device() {
        // 生成 一个不重复 的deviceId
        String deviceId = UUID.randomUUID().toString();
        return deviceId;
    }


    public void sonlinenum(int userId, String agencyMark, ResultDto result) throws Exception {
        User user = userdao.selectId(userId);
        if (user != null) {
            Integer online = InitData.ONLINE_MAP.get(agencyMark).size() + InitData.ROBOT_ONLINE_NUM.get(agencyMark);
            result.setData(online);
            result.setResultData(true, "查询信息成功", 0, null);
        } else {
            result.setResultData(false, "该用户不存在", 2, null);
        }

    }

    // 退出
    public void Logout(int userId, int loginType, ResultDto result, String agencyMark) throws Exception {
        // 先客户自主选择退出，需要清空用户自身id,并删除自身token 0:正常用户,1:游客
        if (loginType == 0) {
            User user = userdao.selectId(userId);
            if (user != null) {
                InitData.ONLINE_MAP.get(agencyMark).remove(userId);
                InitData.SSO_MAP.remove(userId);
                jedisClient.del(TOKEN + userId);
                CustomerContext customerContext = CustomerContext.getInstance();
                customerContext.userFinishServer(userId);
                result.setResultData(true, "用户登出成功", 0, null);
            } else {
                result.setResultData(false, "该用户不存在", 2, null);
            }
        } else {
            TouristData.touristInfo.remove(userId);
            TouristData.touristBetting.remove(userId);
            TouristData.touristWin.remove(userId);
            TouristData.touristPc28Betting.remove(userId);
            TouristData.touristPc28Win.remove(userId);
            jedisClient.del(TOKEN + userId);
        }
    }

    // 心跳包
    public void heartbeat(int userId, String deviceId, ResultDto result) {
        JSONObject jObject = new JSONObject();
        // 覆盖用户的时间戳
        User user = userdao.selectId(userId);
        if (user.getState().equals("0")) {
            jObject.put("result", "2");
            jObject.put("msg", "用户被冻结，请联系客服");
            result.setResultData(false, "用户被冻结，请联系客服", 2, null);
            return;
        }

        String agencyMark = "";
        if(user.getAgencyId().length() != 5){
          agencyMark =  agencyDao.selectAgency(user.getAgencyId()).getProxyRefAgency()+"";
        }else{
            agencyMark = user.getAgencyId();
        }

        InitData.ONLINE_MAP.get(agencyMark).put(userId, (System.currentTimeMillis() / 1000));
        String did = InitData.SSO_MAP.get(userId);
        if (did != null && !deviceId.equals(did)) {
            logger.info("{}--{}", deviceId, did);
            result.setResultData(false, "用户在其他地方登录，强行退出登录", 3, null);
        } else {
            result.setResultData(true, "正常", 0, null);
        }
    }

    public void updatePasswordByUserId(String username, String oldPassword, String newPassword, ResultDto result) {
        Loaclauth selectphone = loaclauthdao.selectphone(username);
        if (selectphone == null) {
            result.setResultData(false, "该用户不存在", 2, null);
        } else {
            if (selectphone.getPassword().equals(UtilsDto.crypt(oldPassword))) {
                loaclauthdao.updatePasswordByUserId(username, UtilsDto.crypt(newPassword));
                result.setResultData(true, "更新密码成功,请重新登入", 0, null);
            } else {
                result.setResultData(false, "旧密码不匹配,请重新输入", 3, null);
            }

        }
    }

    public void delegateInfo(ResultDto<Map<String, Object>> result, int userId) throws Exception {
        Agency ag = agencyDao.selectDelAgency(userId);
        if (null == ag) {
            throw new Exception("用户不存在");
        }

        String id = ag.getId();

        int amount = userdao.selectDelegateUsersAmount(Integer.parseInt(id));
        double income = agencyDao.selectDelIncomeById(Integer.parseInt(id));
        double daycommission = agencyDao.selectDayCommission(Integer.parseInt(id));
        double totalcommission = agencyDao.selectTotalCommission(Integer.parseInt(id));
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("amount", amount);
        data.put("income", income);
        data.put("daycommission", daycommission);
        data.put("totalcommission", totalcommission);

        result.setData(data);
        result.setResultData(true, "查询信息成功", 0, null);

    }

    public void searchMyTeam(Integer userId, Integer pageNow, Integer pageSize, ResultDto result) {
        PageDto page = new PageDto();
        page.setPageSize(pageSize);
        page.setPageNow(pageNow);
        Agency agency = agencyDao.selectDelAgency(userId);
        int total = userdao.selectDelegateUsersAmount(Integer.parseInt(agency.getId()));
        page.setTotalCount(total);
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("agencyMark", agency.getId());
        List<ProxyTeam> list = userdao.searchByAgencyId(params);
        if (list.size() > 0) {
            list.forEach((k) -> {
                double betTotal = bettinginfoDao.searchBetTotal(k.getUserId());
                k.setBetMoney(DealWithDouble.sum(betTotal, 0, 2, 4));
            });
            result.setData2(list.size());
            result.setData(page);
            result.setResultData(true, "查询信息成功", 0, list);
        } else {
            result.setResultData(false, "nodata", 2, list);
        }


    }

    public void spreadCode(Integer userId, ResultDto result) {
        Agency agency = agencyDao.selectDelAgency(userId);
        if (null != agency) {
            String code = SPREADCODE + agency.getId();
            result.setData(code);
            result.setResultData(true, "生成路径成功", 0, null);
        } else {
            result.setResultData(false, "该用户不是代理", 2, null);
        }
    }

    public void searchProxyIncome(String time, Integer userId, ResultDto result) {
        Agency agency = agencyDao.selectDelAgency(userId);
        if (null != agency) {
            time = time.substring(0, 7);
            double money = accountTransactionDao.searchProxyIncome(time, agency.getId());
            result.setData(DealWithDouble.sum(money, 0, 2, 4));
            result.setResultData(true, "查询信息成功", 0, null);
        } else {
            result.setResultData(false, "该用户不是代理", 2, null);
        }

    }

    public void teamRecord(Integer userId, Integer pageSize, Integer pageNow, ResultDto result) {
        PageDto page = new PageDto();
        Agency agency = agencyDao.selectDelAgency(userId);
        if (null != agency) {
            Map<String, Object> params = new HashMap<>();
            String agencyMark = agency.getId();
            page.setPageNow(-1);
            params.put("page", page);
            params.put("agencyMark", agencyMark);
            List<ProxyTeam> proxyTeams = userdao.searchByAgencyId(params);
            List<String> userIdList = new ArrayList<>();
            Map<Integer,String> map = new HashMap<>();
            proxyTeams.forEach((k) -> {
                userIdList.add(k.getUserId());
                map.put(Integer.parseInt(k.getUserId()),k.getUsername());
            });
            //查询用户的下注信息
            page.setPageSize(pageSize);
            page.setPageNow(pageNow);
            params.put("page",page);
            params.put("list",userIdList);
            List<BetDto> list = bettinginfoDao.searchRecordByUserId(params);
            list.forEach((k)->{
                String s = map.get(k.getUserId());
                k.setProfit(DealWithDouble.sum(k.getProfit(),0,2,4));
                k.setWinMoney(DealWithDouble.sum(k.getWinMoney(),00,2,4));
                k.setBetMoney(DealWithDouble.sum(k.getBetMoney(),0,2,4));
                k.setWinTotal(DealWithDouble.sum(k.getWinTotal(),0,2,4));
                k.setUserName(s);
            });
            result.setResultData(true,"获取信息成功",0,list);
        } else {
            result.setResultData(false, "该用户不是代理", 2, null);
        }
    }
}
